package io.github.kimmking.kkconfig.spring;

import io.github.kimmking.kkconfig.repository.KKRepository;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Description for this class.
 *
 * @Author : kimmking(kimmking@apache.org)
 * @create 2024/4/19 21:12
 */
public class KKConfigServiceImpl implements KKConfigService {

    ApplicationContext applicationContext;
    Map<String, String> config;

    public KKConfigServiceImpl(ApplicationContext applicationContext,Map<String, String> config) {
        this.applicationContext = applicationContext;
        this.config = config;
    }

    public Set<String> getPropertyNames() {
        return this.config.keySet();
    }

    public String getProperty(String name) {
        return this.config.get(name);
    }

    @Override
    public void onRepositoryChange(KKRepositoryChangeEvent<Map<String, String>> event) {
        System.out.println("config is changed, and new config: " + event.config());
        Set<String> changedKeys = calcChangedKeys(this.config, event.config());
        System.out.println("publishEvent changedKeys: " + changedKeys);
        this.config = event.config();
        if(!changedKeys.isEmpty())
            applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));
    }

    private Set<String> calcChangedKeys(Map<String, String> oldConfigs,
                                        Map<String, String> newConfigs) {
        if(oldConfigs.isEmpty()) return newConfigs.keySet();
        if(newConfigs.isEmpty()) return oldConfigs.keySet();
        Set<String> news = newConfigs.keySet().stream()
                .filter(key -> !newConfigs.get(key).equals(oldConfigs.get(key)))
                .collect(Collectors.toSet());
        oldConfigs.keySet().stream()
                .filter(key -> !newConfigs.containsKey(key))
                .forEach(news::add);
        return news;
    }
}
